package com.demo.web.security;


import com.demo.web.httpTool.httpResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
//认证失败会调用
public class AppAuthenticationfailureHandler implements AuthenticationFailureHandler {
    @Autowired
    //序列化以及反序列化
    private ObjectMapper objectMapper;


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        httpResult httpResult= com.demo.web.httpTool.httpResult.builder().code(0).message("登录失败").data(null).build();

        String jsontext=objectMapper.writeValueAsString(httpResult);

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        PrintWriter printWriter=response.getWriter();

        printWriter.println(jsontext);
        printWriter.flush();
    }
}
